package org.elanfox.cloud.common.web.base;

import lombok.extern.slf4j.Slf4j;
import org.elanfox.cloud.common.base.ApiResult;
import org.elanfox.cloud.common.enums.CommonCode;
import org.elanfox.cloud.common.exception.ApiException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author allan
 * @version 1.0.0
 * @date 2/26/21
 */
@Controller
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 所有异常统一
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ApiResult<Void> runtimeExceptionHandler(Exception ex) {
        log.error(ex.getMessage(), ex);

        if (ex instanceof ApiException) {
            ApiException apiException = (ApiException) ex;
            return apiException.getApiResult();
        }

        return ApiResult.exception(CommonCode.SYSTEM_EXCEPTION, ex.getMessage());
    }
}
